package com.lottery.ruok.lottrey.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.BetDetailActivity;
import com.lottery.ruok.lottrey.activity.FilterOrderActivity;
import com.lottery.ruok.lottrey.adapter.ChildOrderAdapter;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.eventbusObject.CancelOrder;
import com.lottery.ruok.lottrey.eventbusObject.GotoBuyPage;
import com.lottery.ruok.lottrey.eventbusObject.OrderFilter;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetOrderRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetOrderResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import utils.Utils;

import static com.lottery.ruok.lottrey.R.id.listview;

/**
 * Created by ASUS on 2017/7/27.
 * 投注记录的子fragment，列表展示
 */

public class ChildOrderFragment extends BaseMainFragment {
    @BindView(R.id.filter)
    ImageView filter;
    private GetOrderResponse getOrderResponse;
    ChildOrderAdapter myAdapter;

    @BindView(listview)
    ListView listView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private int index;

    private int mPage = 0;
    private final int pageNum = 10;
    private boolean isInitData = true;

    private View no_net_view;
    private TextView no_net_button;

    private String mStart;
    private String mEnd;
    private String mItemCode;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.order_child_fragment, container, false);

        ButterKnife.bind(this, view);

        isPrepared = true;
        lazyLoad();
        return view;
    }

    private boolean isPrepared;
    private boolean mHasLoadedOnce;

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }

        init();

        mHasLoadedOnce = true;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CancelOrder event) {
        isInitData = false;
        onRefreshs(0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddBetSuccess event) {
        isInitData = false;
        onRefreshs(0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OrderFilter event) {
        mStart = event.getStart();
        mEnd = event.getEnd();
        mItemCode = event.getCode();
        if (mStart != null && mEnd != null && mStart.equals(mEnd)) {
            mStart = mStart + " 00:00:00";
            mEnd = mEnd + " 23:59:59";
        } else {
            isInitData = false;
            onRefreshs(0);
            return;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = format.parse(mStart);
            Date date2 = format.parse(mEnd);
            if (date1.compareTo(date2) > 0) {
                Utils.showToast("起始时间不能大于截止时间");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isInitData = false;
        onRefreshs(0);
    }

    public void onRefreshs(final int page) {
        String status;//1待開獎 2已中奖 3未中奖 4已取消 5已撤單
        switch (index) {
            case 0:        // 第一頁: 全部訂單
                status = "0";
                break;
            case 1:  // 第二頁: 已中獎
                status = "2";
                break;
            case 2:  // 第三頁: 待開獎
                status = "1";
                break;
            default:                 // 第四頁: 合併已取消和已撤單
                status = "4,5";
                break;
        }

        RetrofitBase.getRetrofit().create(GetOrderRequest.class).getResult(status, UserInfo.getUniqueId(), UserInfo.getToken(), pageNum + "", page * 10, mStart, mEnd, mItemCode)
                .compose(RxHelper.<GetOrderResponse>handleResult())
                .subscribe(new RxSubscribe<GetOrderResponse>(getActivity()) {
                    @Override
                    protected void _onNext(GetOrderResponse g) {
                        if(g.getList() != null && g.getList().size() < pageNum){
                            mRefreshLayout.setEnableLoadMore(false);
                        }else{
                            mRefreshLayout.setEnableLoadMore(true);
                        }
                        if (page == 0) {
                            mRefreshLayout.finishRefresh();
                            getOrderResponse = g;
                        } else {
                            if (getOrderResponse != null && getOrderResponse.getList() != null && g != null && g.getList() != null) {
                                getOrderResponse.getList().addAll(g.getList());
                            }
                        }

                        if (getOrderResponse != null && getOrderResponse.getList() != null) {
                            if (myAdapter == null && getActivity() != null) {
                                myAdapter = new ChildOrderAdapter(getActivity(), getOrderResponse);
                                listView.setAdapter(myAdapter);
                            } else {
                                if (myAdapter != null) {
                                    myAdapter.setDatas(getOrderResponse);
                                    myAdapter.notifyDataSetChanged();
                                    mRefreshLayout.finishLoadMore();
                                }
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        if(isInitData){
                            return true;
                        }
                        return false;
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();

                        if (page != 0) {
                            mPage = page;
                        } else {
                            mPage = 0;
                        }

                        if (page == 0) {
//                            swipeRefreshLayout.endRefreshing();

                            //在第一页数据返回来为空时 显示缺省页面
                            if (getView() != null) {
                                if (getOrderResponse.getList().size() == 0 && myAdapter.getCount() == 0) {
                                    getView().findViewById(R.id.lyEmpty).setVisibility(View.VISIBLE);
                                    View views = getView().findViewById(R.id.btnFind);
                                    views.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            EventBus.getDefault().post(new GotoBuyPage());
                                            getActivity().finish();
                                        }
                                    });
                                } else {
                                    getView().findViewById(R.id.lyEmpty).setVisibility(View.GONE);
                                }
                            }
                        } else {
//                            swipeRefreshLayout.endLoadingMore();
                        }

                        if (no_net_view != null) {
                            no_net_view.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                     /*   if (page == 0) {
                            swipeRefreshLayout.endRefreshing();
                        } else {
                            swipeRefreshLayout.endLoadingMore();
                        }*/

                        if (getView() != null) {
                            getView().findViewById(R.id.lyEmpty).setVisibility(View.GONE);
                        }

                        if (myAdapter == null || myAdapter.getCount() == 0) {
                            mRefreshLayout.finishRefresh();
                            if (no_net_view == null) {
                                if (getView() != null) {
                                    ViewStub stub = getView().findViewById(R.id.no_net_viewstub);
                                    View view = stub.inflate();

                                    if (view != null) {
                                        no_net_view = view.findViewById(R.id.no_net_view);
                                        no_net_button = view.findViewById(R.id.no_net_button);
                                        no_net_button.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                isInitData = true;
                                                onRefreshs(0);
                                            }
                                        });
                                    }
                                }
                            } else {
                                no_net_view.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mRefreshLayout.finishLoadMore();
                            if (no_net_view != null) {
                                no_net_view.setVisibility(View.GONE);
                            }
                        }
                    }
                });
    }

    private void init() {
        index = getArguments().getInt("index");
  /*      // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(getContext(), true);
        // 设置下拉刷新和上拉加载更多的风格
        swipeRefreshLayout.setRefreshViewHolder(refreshViewHolder);

        swipeRefreshLayout.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                onRefreshs(mPage + 1);
                return true;
            }

            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                onRefreshs(0);
            }
        });*/
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableRefresh(true);//启用刷新
                isInitData = false;
                onRefreshs(0);

            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableLoadMore(true);//启用加载
                isInitData = false;
                onRefreshs(mPage + 1);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), BetDetailActivity.class);
                intent.putExtra("order_id", getOrderResponse.getList().get(i).getOrder_no());
                intent.putExtra("no", getOrderResponse.getList().get(i).getPeriod_no());
                intent.putExtra("lotteryType", getOrderResponse.getList().get(i).getName());
                intent.putExtra("item_name", getOrderResponse.getList().get(i).getItem_name());
                intent.putExtra("number", getOrderResponse.getList().get(i).getPrize_num());
                intent.putExtra("condition", getOrderResponse.getList().get(i).getStatus());
                intent.putExtra("betNum", getOrderResponse.getList().get(i).getPick_number());
                intent.putExtra("bet_time", getOrderResponse.getList().get(i).getCreated_at());
                intent.putExtra("bet_money", getOrderResponse.getList().get(i).getAmount());
                intent.putExtra("bet_count", getOrderResponse.getList().get(i).getNote_count());
                intent.putExtra("back", getOrderResponse.getList().get(i).getRakeback());
                intent.putExtra("odd", getOrderResponse.getList().get(i).getOdds());
                intent.putExtra("win_amount", getOrderResponse.getList().get(i).getWin_amount());
                intent.putExtra("win_note_count", getOrderResponse.getList().get(i).getWin_note_count());
                intent.putExtra("position",getOrderResponse.getList().get(i).getPosition());
                intent.putExtra("order_status",getOrderResponse.getList().get(i).getOrder_status());
                startActivity(intent);
            }
        });
        isInitData = true;
        onRefreshs(0);
    }

    @OnClick(R.id.filter)
    public void onViewClicked() {
        //sendAnalyticMsg("lottery_" + ((OrderActivity)getActivity()).ANALYTIC_VERSION + "_betrecord_search_jump");

        Intent intent = new Intent(getActivity(), FilterOrderActivity.class);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
    }
}
